package com.tjvib.presenter;

import static com.tjvib.Constants.SUCCESS;

import com.tjvib.common.Callback;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.DataSetManager;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.activity.InterceptActivity;
import com.tjvib.widget.AndroidScheduler;

import org.json.JSONException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class InterceptPresenter extends BasePresenter {

    private static final String TAG = "InterceptPresenter";

    private InterceptActivity view;

    public InterceptPresenter(InterceptActivity view) {
        this.view = view;
    }

    public void initDataSetContent(Callback callback) {
        RetrofitHelper.getInstance().create()
                .getDataSetContent("" + UserManager.getInstance().getUserId(),
                        "" + DataSetManager.getInstance().getDataSetInfo().getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse value) {
//                        LogUtil.i("onNext "+value.getData()+" "+value.getMessage());
                        if (value.getCode() == SUCCESS) {
                            try {
                                DataSetManager.getInstance().setDataSetContent(String.valueOf(value.getData()));
                                callback.onSuccess("sucess", null);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                callback.onError(e.getMessage(), null);
                            }
                        } else {
                            callback.onFail("fail", null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e.getMessage(), null);
                        LogUtil.e(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    String getTag() {
        return TAG;
    }

}
